package com.jl.thread.create;

import java.util.concurrent.*;

/**
 * 同时复写thread的run和Runnable的run
 */
public class ThreadDemo1 {

    public static void main(String[] args) throws Exception {

        new ThreadDemo1().callableTest();

    }

    private void threadTest(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("runnable--------");
            }
        }){
            @Override
            public void run() {
                System.out.println("thread----------");
            }
        }.start();
    }

    private void callableTest() throws ExecutionException, InterruptedException {

        FutureTask futureTask = new FutureTask(new Callable() {
            @Override
            public String call() throws Exception {
                Thread.sleep(5000);
                System.out.println("futureTask----calld方法执行了: thradName=" + Thread.currentThread().getName());
                return "call方法返回值";
            }
        });
        //通过new一个对象的方法可以直接创建一个FutureTask实例，如果直接调用run方法将直接在当前线程中运行，不会开启新线程。
        futureTask.run();
        //futureTask.get（）方法会保证线程在执行完之前是阻塞的。
        System.out.println("获取返回值: " + futureTask.get());

        FutureTask futureTask1 = new FutureTask(new Callable() {
            @Override
            public String call() throws Exception {
                Thread.sleep(3000);
                System.out.println("futureTask1111---calld方法执行了: thradName=" + Thread.currentThread().getName());
                return "call方法返回值1";
            }
        });
        futureTask1.run();
        System.out.println("获取返回值1: " + futureTask1.get());
    }

    //使用ExecutorService或者线程可以让FutureTask进行托管进行，示例如下：
    public void threadPoolSubmitFutureTask(){

        FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return null;
            }
        });

        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<?> submit = executorService.submit(futureTask);

    }

    public void threadFutureTask(){
        FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return null;
            }
        });
        //托管给单独线程处理
        new Thread(futureTask).start();
    }

}
